<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="人员名称" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="日期">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd HH:mm:ss" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px"
          :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>
      <el-form-item> -->
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['cultivate:userRecord:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['cultivate:userRecord:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cultivate:userRecord:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['cultivate:userRecord:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="printBox"
          v-hasPermi="['cultivate:userRecord:print']">打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table @selection-change="handleSelectionChange" fit v-loading="loading" border :data="dataList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" />
      <el-table-column show-overflow-tooltip label="状态" width="150">
        <template slot-scope="scope">
          <el-tag size="mini">{{ scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="培训人员" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ handleString(scope.row.contentList) || "--" }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column show-overflow-tooltip  align="center" label="创建时间" prop="createTime" /> -->
      <el-table-column label="录入时间" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.contentList[0].operTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['cultivate:userRecord:info']"
            @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['cultivate:userRecord:edit']">补充信息</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['cultivate:userRecord:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 打印模板位置 -->
    <PrintBox :pageNum="queryParams.pageNum" :total="total" :printRow="printList" :isVertical="false" id="printBox"
      :checkNum="10" :checkLabel="'contentList'">
      <template slot="title" slot-scope="scope">
        人员培训登记表STET/B/14-6
      </template>
      <template slot-scope="scope">
        <!-- 表格  class  table-page  必须-->
        <table style="border-collapse: collapse" border="1" cellspacing="0" class="table-page">
          <thead>
            <tr class="table_header">
              <th style="width: 20mm">序号</th>
              <th style="width: 30mm">姓名</th>
              <th style="width: 20mm">性别</th>
              <th style="width: 25mm">年龄</th>
              <th style="width: 30mm">文化程度</th>
              <th style="width: 20mm">专业</th>
              <th style="width: 20mm">职称</th>
              <th style="width: 40mm">培训内容</th>
              <th style="width: 40mm">培训起止日期</th>
              <th style="width: 32mm">培训时间</th>
              <th style="width: 48mm">主办单位</th>
              <th style="width: 30mm">备注</th>
            </tr>
          </thead>

          <!-- 同列表接口数据 -->
          <tbody>
            <tr v-for="(e, i) in 10">
              <td style="padding: 2mm">
                {{ scope.item.contentList[i] ? i + 1 : "" }}
              </td>
              <td style="padding: 2mm">
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].userName) ||
                  ""
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  scope.item.contentList[i] &&
                  (scope.item.contentList[i].sex == 1 ? "女" : "男")
                }}
              </td>
              <td style="padding: 2mm">
                {{ scope.item.contentList[i] && scope.item.contentList[i].age }}
              </td>
              <td style="padding: 2mm">
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].userDocEducation.length &&
                  scope.item.contentList[i].userDocEducation.slice(-1)[0]
                    .recordName
                }}
              </td>

              <td style="padding: 2mm">
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].specialize &&
                    scope.item.contentList[i].specialize
                      .split(",")
                      .slice(-1)[0]) ||
                  ""
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].professionalLabel &&
                  scope.item.contentList[i].professionalLabel
                    .split(",")
                    .slice(-1)[0]
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  scope.item.contentList[i] && scope.item.contentList[i].content
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].startDate
                }}{{
  scope.item.contentList[i] &&
  scope.item.contentList[i].startDate
  ? "-"
  : ""
}}{{
  scope.item.contentList[i] && scope.item.contentList[i].endDate
}}
              </td>
              <td style="padding: 2mm">
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].operTime) ||
                  ""
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].organ) ||
                  ""
                }}
              </td>
              <td style="padding: 2mm">
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].remark) ||
                  ""
                }}
              </td>
            </tr>
          </tbody>
        </table>
        <!-- 底部信息位置 -->
        <div class="page-bottom" style="page-break-after: always">
          <div style="display: flex; text-align: left">
            <div style="width: 30%">填表人:
              <!-- {{ scope.item}} -->
              <template>
                <img style="width: 80px; " :src="baseUrl + scope.item.esign" />
              </template>
            </div>
            <div style="width: 30%;display: flex;align-items: center;">审核人:
              <template v-if="CheckApprove(scope, 'jsfzr').ShowImg">
                <img style="width: 80px; " :src="CheckApprove(scope, 'jsfzr').ApproveImg" />
              </template>
            </div>
            <div style="width: 30%">日期:{{ checkHistoryNode(scope, "jsfzr").endTime }}</div>
          </div>
          <div class="desc">注：本表格自2021年6月1日起生效</div>
        </div>
      </template>
    </PrintBox>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import { listUserRecord, delUserRecord } from "@/api/cultivate/userRecord.js";
import { deptTreeSelect } from "@/api/system/user.js";
import printStyle from "@/utils/print.js";

export default {
  name: "userRecord",
  dicts: ["sys_device_check_type"],

  data() {
    return {
      baseUrl: this.$VUE_APP_IMG_API,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      dataList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        operUserId: undefined,
        licenseNum: undefined,
        checkDate: null,
      },
      // 日期范围
      dateRange: [],

      userList: [],
      deptOptions: [],
      infos: [],
      printList: [],
    };
  },
  created() {
    const str = sessionStorage.getItem('queryParams');
    if (str) {
      this.queryParams = JSON.parse(str);
      setTimeout(() => {
        sessionStorage.removeItem('queryParams');
      }, 500)
    }
    this.getList();
    this.getDeptTree();
  },
  methods: {
    printBox() {
      console.log(this.infos, 'this.infos');
      console.log(this.dataList, 'this.dataList');

      //infos  勾选的数据 如果有勾选就打印勾选。
      let result
      let tempArr = [];
      let Data = [];
      if (this.infos.length) {
        result = this.infos

      } else {
        //反之打印当前整个列表      
        result = this.dataList;
        //  console.log( this.dataList);                                       
        // this.printList = this.dataList;
      }
      for (let i = 0; i < result.length; i++) {
        console.log(result, 'result');
        result[i].contentList.forEach(item => {
          let obj = item
          console.log(result[i].wfDetailVo);
          if (tempArr.indexOf(obj.operTime) === -1 && result[i].statusName == '已完成') {
            console.log(result[i].statusName, '=====');
            Data.push({ operTime: obj.operTime, wfDetailVo: result[i].wfDetailVo, contentList: [obj], esign: result[i].esign });
            tempArr.push(obj.operTime);
            tempArr.push(obj.wfDetailVo);

          } else {
            for (let j = 0; j < Data.length; j++) {
              if (Data[j].operTime == obj.operTime) { Data[j].contentList.push(obj); break; }
            }
            this.$message.error("审核中暂不可打印！");
            return
          }
        })


      }
      console.log(Data, '>>>>>>>>>>>>>>>>');
      this.printList = Data;
      console.log(this.printList);
      setTimeout(() => {
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
        });
      }, 500);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
      .desc{
        text-align: left; font-size: 12px; margin-top: 10px
      }
        table,
      table tr th,
      table tr td {
        border: 1px solid;
        height: 35px;
        padding: 10px;

      }
      tr {
        page-break-inside: avoid;
      }
      .table_header{
        font-size:16px;
      }
      `;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.cultivateUserRecordId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      const configId = row.cultivateUserRecordId || this.ids;
      this.$router.push("./addUserRecord?isEdit=true&id=" + configId);
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    handleDetail(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push(
        "./addUserRecord?isInfo=true&id=" + row.cultivateUserRecordId
      );
    },
    handleString(e) {
      return e.map((i) => i.userName).join(",");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configId = row.cultivateUserRecordId || this.ids;
      // let name = this.checkRow(
      //   configId,
      //   this.dataList,
      //   "cultivateUserRecordId",
      //   "DELETE",
      //   "year"
      // );
      this.$modal
        .confirm(
          '是否确认删除培训人员为"' +
          this.handleString(row.contentList) +
          '"的数据项？'
        )
        .then(function () {
          return delUserRecord(configId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleAdd() {
      this.$router.push("./addUserRecord");
    },
    /** 查询列表 */
    getList() {
      this.loading = true;

      listUserRecord(
        this.addDateRangeTime(
          this.queryParams,
          this.dateRange,
          "startEndDate",
          "endEndDate"
        )
      ).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleExport() {
      this.download(
        "system/cultivateUserRecord/export",
        {
          ...this.queryParams,
        },
        `人员培训登记记录表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  img {
    width: 100%;
  }
}

.table-page {
  width: 100%;
}
</style>
